package com.example.trans.demos.controller;

import com.example.trans.demos.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.beans.Transient;

@Slf4j
@RequestMapping("/trans")
@RestController
public class TranController {
    @Autowired
    private UserService userService;

    // 正常处理,没有错误
    @Transactional
    @RequestMapping("/registry")
    public String registry(String userName,String password){
        Integer result = userService.insertUser(userName,password);
        log.info("用户插入成功,result " + result);

        return "注册成功";
    }

    // 有异常,没有处理
    @Transactional
    @RequestMapping("/t2")
    public String registry3(String userName,String password){
        Integer result = userService.insertUser(userName,password);
        int a = 10 / 0;
        log.info("用户插入成功,result " + result);

        return "注册成功";
    }

    // 抛出异常并且捕获了异常
    @Transactional
    @RequestMapping("/t3")
    public String registry2(String userName,String password) {
        Integer result = userService.insertUser(userName, password);
        try {
            int a = 10 / 0;
        } catch (Exception e){
            log.info("程序出错");
        }
        log.info("用户插入成功,result " + result);

        return "注册成功";
    }

    // 程序报错,重新抛出异常
    // 事务回滚
    @Transactional
    @RequestMapping("/t4")
    public String registry4(String userName,String password) {
        Integer result = userService.insertUser(userName, password);
        try {
            int a = 10 / 0;
        } catch (Exception e){
            log.info("程序出错");
            throw e;
        }
        log.info("用户插入成功,result " + result);

        return "注册成功";
    }

    // 程序报错
    // 手动回滚
    @Transactional
    @RequestMapping("/t5")
    public String registry5(String userName,String password) {
        Integer result = userService.insertUser(userName, password);
        try {
            int a = 10 / 0;
        } catch (Exception e){
            log.info("程序出错");
            // 当前事务回滚
            // 当前的事务的状态设置为回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        log.info("用户插入成功,result " + result);

        return "注册成功";
    }
}
